package org.jdns.jfreechess.server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundByteHandlerAdapter;

import org.jdns.jfreechess.timeseal.Timeseal;

public class TimesealHandler extends ChannelInboundByteHandlerAdapter {
  @Override
  public void inboundBufferUpdated(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    int end = in.readableBytes() + in.readerIndex();

    while (in.readableBytes() > 0) {
      int linefeed = -1;
      boolean linefeedFound = false;
      for (int i = in.readerIndex(); i < end; i++) {
        if (in.array()[i] == 0x0a) {
          linefeed = i;
          linefeedFound = true;
          break;
        }
      }

      if (linefeed == -1) {
        linefeed = end;
      }

      if (linefeed - in.readerIndex() - 1 > 0) {
        byte[] bytes = new byte[linefeed - in.readerIndex()];
        in.readBytes(bytes);
        ctx.nextInboundMessageBuffer().add(Timeseal.decrypt(bytes));
      }

      if (linefeedFound) {
        in.skipBytes(1);
      }
    }
    ctx.fireInboundBufferUpdated();
  }
}
